/**
 *  学习目标：Todos 案例
 */
import React, { useState } from "react";
import "./styles/base.css";
import "./styles/index.css";
import { useSelector } from "react-redux";
import {
  addActionCreator,
  dltActionCreator,
  updateActionCreator,
} from "./store/action/todo";
import { useDispatch } from "react-redux";

export default function App(params) {
  return (
    <section className="todoapp">
      {/* 头部 */}
      <Header></Header>
      {/* 主体 */}
      <Main></Main>
      {/* 底部 */}
      <Footer></Footer>
    </section>
  );
}
function Footer() {
  return (
    <footer className="footer">
      <span className="todo-count">
        <strong>1</strong> 剩余
      </span>
      <ul className="filters">
        <li>
          <a className="all selected" href="#/">
            全部
          </a>
        </li>
        <li>
          <a className="active" href="#/active">
            未完成
          </a>
        </li>
        <li>
          <a className="completed" href="#/completed">
            已完成
          </a>
        </li>
      </ul>
      <button className="clear-completed">清除已完成</button>
    </footer>
  );
}

function Main() {
  // 4. 按模块名取出使用
  const { list } = useSelector((state) => state.todo);
  // console.log(list);
  const dispatch = useDispatch();
  return (
    <section className="main">
      <input id="toggle-all" className="toggle-all" type="checkbox" />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {list.map((item) => {
          return (
            <li key={item.id} className={item.isDone ? "completed" : ""}>
              <div className="view">
                <input
                  checked={item.isDone}
                  onChange={() => {
                    dispatch(updateActionCreator(item.id));
                  }}
                  className="toggle"
                  type="checkbox"
                />
                <label>{item.task}</label>
                <button
                  onClick={() => {
                    dispatch(dltActionCreator(item.id));
                  }}
                  className="destroy"
                ></button>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}

function Header() {
  const dispatch = useDispatch();

  const [task, setTask] = useState("");
  // store.subscribe(() => {
  //   console.log("改变了");
  // });
  const keyDown = (e) => {
    // console.log(e);
    if (e.keyCode === 13) {
      // console.log("回车了");
      dispatch(addActionCreator({ id: Date.now(), task, isDone: false }));
      setTask("");
    }
  };
  return (
    <header className="header">
      <h1>todos</h1>
      <input
        onKeyDown={keyDown}
        onChange={(e) => {
          setTask(e.target.value);
        }}
        value={task}
        className="new-todo"
        placeholder="需要做什么"
        autoFocus
      />
    </header>
  );
}
